<?php

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

//Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
//    return $request->user();
//});

Route::post('/v1/login',function(Request $request){
    $email = $request->get("email");
    $password = $request->get("password");
    $keep_mi_in_for = $request->get("keep_me_in_for");

    $user = User::where("email",$email)->firstOrFail();
    if($user && password_verify($password,$user->password)){
        $token = \Illuminate\Support\Str::random(60);
        $user->token = password_hash($token,PASSWORD_DEFAULT);
        $user->token_generated_at = now();
        if($keep_mi_in_for){
            $user->token_valid_duration = $keep_mi_in_for + 0;
        }
        $user->save();
        return response()->json(
            [
                "msg"=> "Success",
                "data" => [
                    "first_name"=>$user->first_name,
                    "last_name"=>$user->last_name,
                    "email"=>$user->email,
                    "token"=>$token,
                    "role"=>$user->role,
                ]
            ],
            200
        );

    }
    return response()->json([
        "msg"=> "Unauthorized"
    ],401);

});
